package bsf.compress;

import bsf.base.BsfException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * Created by Administrator on 2016/3/8.
 */
public class GzipProvider
{
    /**
     Compresses the string.
     @return
     */
    public byte[] compress(byte[] data)
    {
        try {
            try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
                    gzip.write(data);
                }
                return out.toByteArray();
            }
        }
        catch (IOException e)
        {
            throw new BsfException("GzipProvider压缩",e,this.getClass());
        }
    }

    /**
     Decompresses
     */
    public byte[] decompress(byte[] data)
    {
        try {
            try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                try (ByteArrayInputStream in = new ByteArrayInputStream(data)) {
                    try (GZIPInputStream gunzip = new GZIPInputStream(in)) {
                        byte[] buffer = new byte[256];
                        int n;
                        while ((n = gunzip.read(buffer)) >= 0) {
                            out.write(buffer, 0, n);
                        }
                        return out.toByteArray();
                    }
                }
            }
        }
        catch (IOException e)
        {
            throw new BsfException("GzipProvider解压缩",e,this.getClass());
        }
    }
}
